import frappe
from frappe.model.document import Document
from frappe import _

@frappe.whitelist()
def create_material_transfer_batch(items, stock_entry_type, posting_date=None, posting_time=None):
    """
    创建一个包含多个物料的 Stock Entry 单据，移动类型由调用方传入（支持批号）。
    """
    try:
        import json
        if isinstance(items, str):
            items = json.loads(items)

        if not stock_entry_type:
            return {
                "status": "error",
                "message": "参数 stock_entry_type 是必传项，不能为空"
            }

        doc = frappe.new_doc("Stock Entry")
        doc.stock_entry_type = stock_entry_type  # 必须传入
        doc.purpose = stock_entry_type
        doc.posting_date = posting_date or frappe.utils.today()
        doc.posting_time = posting_time or frappe.utils.nowtime()

        for row in items:
            item_code = row["item_code"]
            qty = row["qty"]
            from_warehouse = row.get("from_warehouse")
            to_warehouse = row.get("to_warehouse")
            batch_no = row.get("batch_no")  # 可选

            item_detail = frappe.get_doc("Item", item_code)

            item_row = {
                "item_code": item_code,
                "qty": qty,
                "uom": item_detail.stock_uom,
                "stock_uom": item_detail.stock_uom,
                "conversion_factor": 1,
                "s_warehouse": from_warehouse,
                "t_warehouse": to_warehouse
            }

            if item_detail.has_batch_no and not batch_no:
                return {
                    "status": "error",
                    "message": f"物料 {item_code} 启用了批号管理，但未提供批号"
                }
            if item_detail.has_batch_no and batch_no:
                item_row["batch_no"] = batch_no

            doc.append("items", item_row)

        doc.insert()
        doc.submit()

        return {
            "status": "success",
            "message": f"Stock Entry {doc.name} created successfully with multiple items",
            "stock_entry": doc.name
        }

    except Exception as e:
        frappe.log_error(frappe.get_traceback(), "Material Transfer Batch Error")
        return {
            "status": "error",
            "message": str(e)
        }

